Hands-On Serverless Applications with Kotlin by Hardik Trivedi

Hands-On Serverless Applications with Kotlin by Hardik Trivedi

Author:Hardik Trivedi [Hardik Trivedi]
Language: eng
Format: epub
Publisher: Packt Publishing
Published: 2018-09-28T16:30:38+00:00


Lambda functions

One of the top-selling points of Kotlin is that it supports a function as a type. This means functions can be saved/held as an object or can be passed as a parameter, just like an object. You can think of lambda functions as functions without a name. We used to call them anonymous functions. Kotlin's lambda functions are similar to Java's lambda functions.

They are very useful. They save us a lot of time by not writing specific functions in an abstract class or an interface.

For example, a button's onClick event is one of the boring and stereotype works in Android. But Kotlin does it using lambdas:

createPollButton.setOnClickListener {

presenter.createPoll(pollTitle.text.toString(), pollQuestion.text.toString(), getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE).getString("userId", ""))

}

Let's say you want to write a function that adds two numbers but in a lambda style. The code can be written as follows:

val sum = { num1: Int, num2: Int -> num1 + num2 }

And we can call the preceding function using the following code:

val sumAns=sum(10,20)

The val sum just looks like a property, but it's actually a function. Many developers also use invoke functions, which trigger the lambda function. Using invoke, the same code can be rewritten like:

val sumAns=sum.invoke(10,20)



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.